/*
 * Copyright 2007 - The JDPF Project Team (http://www.jdpf.org) 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package org.jdpf.core.plugins.registration;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.jdpf.core.plugins.blocks.AbstractTransitionPlugin;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

/**
 * Simple impelemtation of the registration service. Mainly context management.
 * 
 * @author Paolo Ciccarese 
 */
public abstract class AbstractRegistrationService implements RegistrationService {

	protected BundleContext bundleContext;
	
	protected Properties properties = new Properties();
	
	private Map<String,ServiceRegistration> registrations=new HashMap<String,ServiceRegistration>();

	/**
	 * @param context	The actual bundle context
	 */
	public void setBundleContext(final BundleContext context) {
		this.bundleContext = context;
	}

	/**
	 * @return	The service registration
	 */
	public ServiceRegistration getServiceRegistration(String id) {
		return registrations.get(id);
	}
	
	/** Unregister a service from OSGi service register
	 * @param serviceId - the id of the service to be unregistered
	 */
	public void unregister(String serviceId){
		ServiceRegistration sr=registrations.get(serviceId);
		registrations.remove(serviceId);
		sr.unregister();
	}
	
	/** Complete a service registration.
	 * @param service - the AbstractTransitionPlugin to be regitered as a service
	 * @param prop - properties for the service
	 * @return the actual service registration
	 */
	public ServiceRegistration doRegistration(AbstractTransitionPlugin service,Properties prop){
		ServiceRegistration sr = bundleContext.registerService(service.getClass()
				.getName(), service, properties);
		String id= sr.getReference().getProperty("service.id").toString();
		service.setServiceId(id);
		registrations.put(id,sr);
		
		return sr;
	}
}
